#include "ThreadingBTree.h"
static BTNode* prev = nullptr;
static void ThreadingInOrder(BTNode* node)
{
	if (node)
	{
		ThreadingInOrder(node->left);
		if (node->left==nullptr) {
			node->lflag = 1;
			node->left = prev;
		}
		if (prev && prev->right == nullptr)
		{
			prev->right = node;
			prev->rflag = 1;
		}
		pre = node;
		ThreadingInOrder(node->right);	
	}
}

static FreeBTNode(BTNode* node)
{
	if (node)
	{
		if (node->lflag==0)
		{
			FreeBTNode(node->left);
		}
		if (node->rflag == 0) {
			FreeBTNode(node->right);
		}
		free(node);
	}
}

void releaseTree(ThreadBTree* tree)
{
	if (tree->root)
	{
		FreeBTNode(tree->root);
		tree->count--;
	}
}

void InOrderThreadingBTree(ThreadBTree* tree)
{
	if (tree)
	{
		ThreadingInOrder(tree->root);	
	}
}

void InOrderTree(ThreadBTree* tree)
{
	BTNode* node = tree->root;
	while (node)
	{
		while (node->lflag == 0)
		{
			node = node->left;
		}
		visitNode(node);
		while (node->rflag && node->right != nullptr)
		{
			node = node->right;
			visitNode(node);
		}
		node = node->right;
	}
}
